/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * seleccionarCita.java
 *
 * Created on 02-may-2011, 14:00:45
 */

package interfaces;


import Controlador.*;
import GestorCitas.Cita;
import GestorCitas.EstadoCita;
import GestorClinico.*;
import GestorClinico.HoraTrabajo;
import GestorUsuarios.PersonalClinica;
import GestorUsuarios.Usuario;
import clinica.ClinicaView;
import clinica.Interfaces;
import clinica.Interfaz;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;

/**
 *
 * @author Victor
 */
public class seleccionarCita extends javax.swing.JPanel {

    private Cita [] citas;
    private ClinicaView app;

    class ComparadorCitas implements Comparator {

    public int compare(Object emp1, Object emp2){
        Date emp1Age = ((Cita)emp1).getFechaCita();
        Date emp2Age = ((Cita)emp2).getFechaCita();

        if(emp1Age.after(emp2Age))
            return 1;
        else if(emp1Age.after(emp2Age))
            return -1;
        else
            return 0;
    }
    }

    /** Creates new form seleccionarCita */
    public seleccionarCita(ClinicaView a) {
        app = a;
        initComponents();

        tabla.setRowHeight(32);
        tabla.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public void rellenarCitas() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        Date ini = null; //Desde la fecha de entrada (fichada)
        PersonalClinica per = (PersonalClinica) Controlador.getUsuarioActivo();
	ControlHorario ch = per.getUltimoControlHorario();
        if ( ch != null) {
            if (!ch.getFechaEntrada().equals(ch.getFechaSalida())){
                app.abrirMensajeError("No se ha fichado entrada, debe fichar para poder pasar consulta.", Interfaces.PRINCIPAL_MEDICO);
                return;
            }
            else ini = ch.getFechaEntrada();
        } else {
            app.abrirMensajeError("No se ha fichado entada, debe fichar para poder pasar consulta.", Interfaces.PRINCIPAL_MEDICO);
            return;
        }
        DateFormat fecha = new  SimpleDateFormat("dd/MM/yyyy, HH:mm");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, 24);
        Date fin = cal.getTime();
        citas = Controlador.consultarCitas(Controlador.getUsuarioActivo().getIdUsuario(), ini, fin, EstadoCita.PENDIENTE);
        // Limpiamos la tabla
        while(((DefaultTableModel)tabla.getModel()).getRowCount()>0)
            ((DefaultTableModel)tabla.getModel()).removeRow(0);
        if (citas != null) {
            Arrays.sort(citas, new ComparadorCitas());
            Usuario u = null;
            for(Cita c:citas) {
                u = Usuario.get(c.getIdPaciente());
                String [] datos = { u.getNombre()+" "+u.getApellidos(),fecha.format(c.getFechaCita())};
                ((DefaultTableModel)tabla.getModel()).addRow(datos);
            }
        } else {
            app.abrirMensajeError("Por ahora no tiene ninguna cita pendiente.", Interfaces.PRINCIPAL_MEDICO);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();

        setName("Form"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(seleccionarCita.class, this);
        jButton1.setAction(actionMap.get("aceptar")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(seleccionarCita.class);
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setToolTipText(resourceMap.getString("jButton1.toolTipText")); // NOI18N
        jButton1.setLabel(resourceMap.getString("jButton1.label")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("cancelar")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setToolTipText(resourceMap.getString("jButton2.toolTipText")); // NOI18N
        jButton2.setLabel(resourceMap.getString("jButton2.label")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize())); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabla.setFont(Interfaz.setFontSize());
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Paciente", "Fecha cita"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setName("tabla"); // NOI18N
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 853, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton3.setAction(actionMap.get("rechazar")); // NOI18N
        jButton3.setFont(Interfaz.setFontSize());
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setToolTipText(resourceMap.getString("jButton3.toolTipText")); // NOI18N
        jButton3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jButton3.setName("jButton3"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 502, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    @Action
    public void cancelar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        app.volver(Interfaces.PRINCIPAL_MEDICO);
    }

    @Action
    public void aceptar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException, ParseException {
        int row = tabla.getSelectedRow();
        if ( row < 0) {
            app.abrirMensajeError("No se seleccionó ninguna cita para pasar consulta.", Interfaces.SELECCIONAR_CITA);
        } else {
            citas[row].setEstado(EstadoCita.EN_CURSO);
            Cita.update(citas[row]);
            app.abrirPantallaCita(citas[row],Interfaces.SELECCIONAR_CITA);
        }
    }

    @Action
    public void rechazar() throws SQLException, NoSuchAlgorithmException, IOException, ClassNotFoundException {
      int row = tabla.getSelectedRow();
        if ( row < 0) {
            app.abrirMensajeError("No se seleccionó ninguna cita para cancelarla.", Interfaces.SELECCIONAR_CITA);
        } else {
            citas[row].setEstado(EstadoCita.NO_LLEVADA_A_CABO);
            Cita.update(citas[row]);
            app.abrirMensajeExito("Cita cancelada correctamente", Interfaces.SELECCIONAR_CITA);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    // End of variables declaration//GEN-END:variables

}
